package com.security.filter;

import com.common.result.Result;
import com.common.util.CustomBeanUtil;
import com.security.domain.authority.CommonUserDetails;
import com.security.service.AuthenticateService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author zdh
 */
@Data
@Slf4j
@RequiredArgsConstructor
public class TokenAuthFilter extends AbstractTokenAuthenticationFilter {
    private final AuthenticateService authenticateService;
    @Autowired(required = false)
    private List<FilterInterceptor> filterInterceptorList;

    /**
     * 认证成功,当前请求还未被处理,进行前置处理
     * @param request
     * @param response
     */
    @Override
    protected void beforeSuccessAuthInvoke(HttpServletRequest request, HttpServletResponse response) {
           if(ObjectUtils.isEmpty(filterInterceptorList)){
               return;
           }
           filterInterceptorList.forEach(filterInterceptor -> filterInterceptor.beforeSuccessAuthInvoke(request,response));
    }

    /**
     * 认证成功,并且当前请求处理完后,进行后置处理
     * @param request
     * @param response
     */
    @Override
    protected void afterSuccessAuthInvoke(HttpServletRequest request, HttpServletResponse response) {
        if(ObjectUtils.isEmpty(filterInterceptorList)){
            return;
        }
        filterInterceptorList.forEach(filterInterceptor -> filterInterceptor.afterSuccessAuthInvoke(request,response));
    }

    /**
     * 对当前用户状态进行检查,如果状态异常,返回false,否则返回true
     *
     * @param userDetails
     * @return
     */
    @Override
    protected boolean userStatusCheck(UserDetails userDetails) {
        //默认只会检查当前账户是否启用
        return userDetails.isEnabled();
    }

    /**
     * @param token 待验证令牌
     * @return 通过解析token来获取当前用户详细信息
     */
    @Override
    protected UserDetails verifyToken(String token) {
        Result result = authenticateService.verifyToken(token);
        if(result==null || result.getData()==null){
            return null;
        }
        return CustomBeanUtil.mapToBean((Map) result.getData(), new CommonUserDetails());
    }
}
